package com.scgaopan.disruptor;

import com.lmax.disruptor.RingBuffer;

import java.nio.ByteBuffer;

/**
 * 生产者，生产longEvent事件
 */
public class LongEventProducer {

    /**RingBuffer是消息存储结构，为环形存储结构，每个单元存储一条消息，类似于队列。当ringbuffer中数据填满之后，
     环就会阻塞，等待消费者消费掉数据，当所有消费者消费掉环中一个数据，新的消息才可以加入环中。每个环插入数据后，
     都会分配一个位置编号，即sequence
     */
    private final RingBuffer<LongEvent> ringBuffer;

    public LongEventProducer(RingBuffer<LongEvent> ringBuffer)
    {
        this.ringBuffer = ringBuffer;
    }


    public void product(ByteBuffer bb)
    {
        long sequence = ringBuffer.next();  // 在ringBuffer中声明了一个sequece就必须发布这个sequece,所以要放在try/finally中执行
        try
        {
            LongEvent event = ringBuffer.get(sequence); // Get the entry in the Disruptor
            // for the sequence
            event.setValue(bb.getLong(0));  // Fill with data
        }
        finally
        {
            ringBuffer.publish(sequence);
        }
    }

}
